/*
 * @Author: linzaifei 1609781601@qq.com
 * @Date: 2024-08-07 13:38:59
 * @LastEditors: linzaifei 1609781601@qq.com
 * @LastEditTime: 2025-08-15 13:41:59
 * @FilePath: /mapbox-vue-h5/src/api/request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import {  useAccountStore} from "@/stores/account";
// 创建请求实例
const instance: AxiosInstance = axios.create({
  baseURL: "/api",
  timeout: 15000, // 15秒超时
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么

    const accountStore = useAccountStore();
    if (accountStore.account.token) {
      config.headers["X-Token-Authorization"] = accountStore.account.token;
    }
    // config.headers['deviceId'] = 'pc_deviceId'
    // config.headers['advertId'] = 'pc_advertId'
    // config.headers['osType'] = 'pc'
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 处理响应数据
    return response.data
  },
  async (error) => {
    // const originalRequest = error.config

    // 统一错误处理
    handleError(error)
    return Promise.reject(error)
  }
)

// 错误处理函数
const handleError = (error: any) => {
  if (error.response) {
    // 服务器返回错误状态码
    switch (error.response.status) {
      case 400:
        console.error('请求错误')
        break
      case 401:
        console.error('未授权访问')
        break
      case 403:
        console.error('拒绝访问')
        break
      case 404:
        console.error('请求地址不存在')
        break
      case 500:
        console.error('服务器内部错误')
        break
      default:
        console.error('其它错误信息')
    }
  } else if (error.request) {
    // 请求已经发出，但没有收到响应
    console.error('网络错误')
  } else {
    // 请求配置发生的错误
    console.error('请求配置错误', error.message)
  }
}


// 请求方法封装
export const request = {
  get: <T>(url: string, config?: AxiosRequestConfig) => 
    instance.get<T, T>(url, config),
  
  post: <T>(url: string, data?: any, config?: AxiosRequestConfig) =>
    instance.post<T, T>(url, data, config),
  
  put: <T>(url: string, data?: any, config?: AxiosRequestConfig) =>
    instance.put<T, T>(url, data, config),
  
  delete: <T>(url: string, config?: AxiosRequestConfig) =>
    instance.delete<T, T>(url, config),

  upload: <T>(
    url: string,
    data: FormData,
    onUploadProgressCallback?: (progressEvent: any) => void,
    config?: AxiosRequestConfig
  ) =>
    instance.post<T, T>(url, data, {
      ...config,
      headers: {
        ...(config?.headers || {}),
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: onUploadProgressCallback,
    }),
}
export {instance}
export default request